//
//  UITextView+TZExtension.m
//  TZOCExtension
//
//  Created by Tim.Z on 2017/1/3.
//  Copyright © 2017年 Tim.Z. All rights reserved.
//

#import "UITextView+TZExtension.h"
#import <objc/runtime.h>
static int kPlaceholderKey;
static int kPlaceholderLabelKey;

@interface UITextView ()<UITextViewDelegate>

@property (nonatomic, strong) UILabel *placeholderLabel;

@end


@implementation UITextView (TZExtension)



- (UILabel *)placeholderLabel{
    return [self tz_getAssociatedValueForKey:&kPlaceholderLabelKey];
}

- (void)setPlaceholderLabel:(UILabel *)placeholderLabel{
    [self tz_setAssociateValue:placeholderLabel withKey:&kPlaceholderLabelKey];
}

- (NSString *)tz_placeholder{
    return [self tz_getAssociatedValueForKey:&kPlaceholderKey];
}

- (void)setTz_placeholder:(NSString *)tz_placeholder{
    [self tz_setAssociateValue:tz_placeholder withKey:&kPlaceholderKey];
    
    [self.placeholderLabel removeFromSuperview];
    UILabel *label = [[UILabel alloc] init];
    label.text = tz_placeholder;
    label.textColor = [UIColor grayColor];
    label.font = self.font;
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    [label sizeToFit];
    label.frame = CGRectMake(5, 6, self.frame.size.width-10, self.frame.size.height-12);
    [label sizeToFit];
    
    [self addSubview:label];
    
    self.placeholderLabel = label;
    
    self.delegate = self;
    [self layoutIfNeeded];
}


- (void)textViewDidChange:(UITextView *)textView{
    self.placeholderLabel.hidden = YES;
    if (self.text.length == 0) {
        self.placeholderLabel.hidden = NO;
    }
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.placeholderLabel.frame = CGRectMake(5, 6, self.frame.size.width-10, self.frame.size.height-12);
    [self.placeholderLabel sizeToFit];
}

@end
